<?php
/**
 * Created by PhpStorm.
 * User: zzw
 * Date: 17-3-19
 * Time: 下午3:45
 */
class pay extends API_Controller
{
    protected $rules = array(
        "pay" => array(
            array(
                'field' => 'rid',
                'label' => '关注用户',
                'rules' => 'trim|required|numeric|callback_rid_check',
            ),
        )
    );

    public function __construct()
    {
        parent::__construct();
        $this->load->model('pay_logs_model', 'mpay_log');
    }
    //充值 --生成订单
    public function recharge() {
        $this->_auto();
        $data = array(
            'uid' => $this->userinfo['id'],
            'type' => $this->data['type'],
            'money' => $this->data['money'],
            'kind' => 1,
            'pay_code'=>get_order_sn('boc_pay_logs','C'),
            'created' => time()
        );
        $detail = $this->mpay_log->create($data);
        if ($detail) {
            $this->vdata['returnCode'] = '200';
            $this->vdata['returnInfo'] = '操作成功';
            $this->vdata['secure'] = JSON_SECURE;
            $this->vdata['content'] = array('order_id'=>$detail,'order_no'=>$data['pay_code']);
        } else {
            $this->vdata['returnCode'] = '200';
            $this->vdata['returnInfo'] = '操作失败';
            $this->vdata['content'] = '';
        }
        $this->_send_json($this->vdata);
    }
    //提现 --生成订单
    public function withdraw() {
        $account = $this->macc->get_one($this->userinfo['id'],'balance');
        $have_money = $account['balance'] * 100;
        $balance_money = $this->data['money'] * 100;
        if($have_money < $balance_money) {
            $this->vdata['returnCode'] = '100002';
            $this->vdata['returnInfo'] = '余额不足';
            $this->vdata['content'] = '';
        } else {
            $this->load->model('withdrawapply_model','mwithdrawapply');
            $this->load->model('balance_detail_model','mbalance_detail');
            $this->_auto();
            $data = array(
                'uid' => $this->userinfo['id'],
                'type' => $this->data['type'],
                'money' => $this->data['money'],
                'partner_trade_no'=>ordernum_time('',true),
                'created' => time()
            );
            $balance = array(
                'uid' => $this->userinfo['id'],
                //'pay_ways' => $this->data['type'],
                'money' => $this->data['money'],
                'pay_code' =>$data['partner_trade_no'],
                'type' =>8,
                'title' =>'提现',
                'status' =>3,
                'created_at' =>$data['created'],
                'payee' =>$this->userinfo['uname'],
                'rid' =>$this->userinfo['id'],
            );
            $flag = true;
            //1 微信 2 支付宝
            if($this->data['type'] == 1) {
                $this->load->model('user_weixin_model','muser_weixin');
                $wx = $this->muser_weixin->get_one(array('uid'=>$this->userinfo['id']),'openid,nickname');
                if(!$wx) {
                    $flag = false;
                } else {
                    $data['openid'] = $wx['openid'];
                    $data['nickname'] = $wx['nickname'];
                    $balance['openid'] = $wx['openid'];
                    $balance['nickname'] = $wx['nickname'];
                }
            } else {
                $data['alipay_num'] = $this->data['alipay_num'];
                $data['alipay_name'] = $this->data['alipay_name'];
                $balance['alipay_num'] = $this->data['alipay_num'];
                $balance['alipay_name'] = $this->data['alipay_name'];
            }
            if(!$flag) {
                $this->vdata['returnCode'] = '10002';
                $this->vdata['returnInfo'] = '此用户未绑定微信，请先绑定';
                $this->vdata['secure'] = JSON_SECURE;
                $this->vdata['content'] = '';
            } else {
                $detail = $this->mwithdrawapply->create($data);
                if ($detail) {
                    $this->mbalance_detail->create($balance);
                    $this->macc->update(array('balance'=>$account['balance']-$this->data['money']),array('id'=>$this->userinfo['id']));
                    $this->vdata['returnCode'] = '200';
                    $this->vdata['returnInfo'] = '操作成功';
                    $this->vdata['secure'] = JSON_SECURE;
                    $this->vdata['content'] = array('order_id'=>$detail,'order_no'=>$data['partner_trade_no'],'time'=>date('Y-m-d :H:i:s',$data['created']));
                } else {
                    $this->vdata['returnCode'] = '200';
                    $this->vdata['returnInfo'] = '操作失败';
                    $this->vdata['content'] = '';
                }
            }
        }

        $this->_send_json($this->vdata);
    }
    /**
     * 支付宝签名 alipay.trade.app.pay
     */
    public function AliSign() {
        $this->_auto();
        $notifyUrl = site_url('notify/aliApi');
        //$notifyUrl = 'http://xjw.hzboc.com/NewZbq/web/api/index.php/test';
        $trade_no = $this->data['trade_no'];
        $amount = $this->data['amount'];
        $subject = $this->data['subject'];
        require_once LIBS_PATH."alipay_api/alipay.config.php";
        require_once LIBS_PATH."alipay_api/lib/alipay_rsa.function.php";
        //require_once LIBS_PATH."alipay_api/lib/alipay_notify.class.php";
        $paydata=array(
            'service'=>$alipay_config['service'],
            'partner'=>$alipay_config['partner'],
            '_input_charset'=>$alipay_config['input_charset'],
            'out_trade_no'=>$trade_no,
            'subject'=>$subject,
            'payment_type'=>'1',
            'seller_id'=>$alipay_config['seller_id'],
            'total_fee'=>$amount,
            'body'=>$subject,
            'it_b_pay'=>'1d',
            'notify_url'=> $notifyUrl ,
            //'show_url'=>urlencode($notifyUrl),
        );
        //生成需要签名的订单
        $orderInfo = $this->createLinkstring($paydata);
        //签名
        //$sign = rsaSign($orderInfo,trim($alipay_config['private_key_path']));
        //$sign = $this->rsaSign($orderInfo);
        $sign = $this->rsaSignPath($orderInfo,$alipay_config['private_key_path']);
        //生成订单
        echo $orderInfo.'&sign="'.$sign.'"&sign_type="RSA"';

    }
    // 对签名字符串转义
    function createLinkstring($para) {
        $arg  = "";
        while (list ($key, $val) = each ($para)) {
            $arg.=$key.'="'.$val.'"&';
        }
        //去掉最后一个&字符
        $arg = substr($arg,0,count($arg)-2);
        //如果存在转义字符，那么去掉转义
        if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}
        return $arg;
    }
// 签名生成订单信息
    function rsaSign($data) {
        $priKey = "-----BEGIN RSA PRIVATE KEY-----
MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALVBpvNt3yELu/odjbdr82PtOQdGz6NbtfgqQ47RGORKrtr3pFrvGMKG00oSO5L0CO+WG1jS6asAfLLVgT9sQCFuG8UuAKVrM5O6pt929uIqZHbAjNph5rs7H5gJ//tFJnALdgtgzi9tbJFzsihndiO8cCr2nLNH9qHfmP8sA3yzAgMBAAECgYA+G1jRYHxsHlEyyp2ck+i5/Lblv2W2W95mQlUTwqH813pCnUg7wGGDhh8v6j9vgx7suUp1jQ90AJ65yF6ZFMaEGaEfS+SYRpeaNiRQWPb9lQBN8oLTlWWg6YdafcTGEYFI6d2eSJCvzY7Efr9oNhgp9Ho1p5GCklY6ecercNIzQQJBAO0dqlz7Qg7UYjMIVIgllWvxBII+keVFeY7BZtXwLvoK668HmP9AHipGhsk56sDBt3ZY7NodPkZjmIqcCfze7hcCQQDDsR70XM1Mr8488V67S/sqRi1a175/cXyZNnlgNg77Cm9ZWOv43lHaMWsX3arwHfECSAK4L9CHFTdMBqgdNAPFAkBThNt5HNdLuetM5mY//lz/REm+RqPFCg+jBORf/tXNJQOXByoQ3ljBs03OmyPg+VrRyMjEmwBQcsxMJmIuO6fJAkBF89Ov4FiW+CVODa4iX7fJ1coytfpnziaPEjTzGn/iZ0mEc8/uZ3J0/8NbhaasLNfRS/KE6rqs/v2EVMDVp5lNAkBLv3Jruwg8f6PjBQ2R5HZUZaSTXRvvOcf5O9zTltuAZs0hDGtsF0cMDZZAw7a160V9yBWONUEvr3WUwq184b/Q
-----END RSA PRIVATE KEY-----";
        $res = openssl_get_privatekey($priKey);
        openssl_sign($data, $sign, $res);
        openssl_free_key($res);
        $sign = base64_encode($sign);
        $sign = urlencode($sign);
        return $sign;
    }
    function rsaSignPath($data,$path) {
        $fp = fopen ($path, "r");

        $raw_key_data = fread ($fp, filesize ($path));
        fclose ($fp);
        $res = openssl_get_privatekey($raw_key_data);
        openssl_sign($data, $sign, $res);
        openssl_free_key($res);
        $sign = base64_encode($sign);
        $sign = urlencode($sign);
        return $sign;
    }
    /**
     * 对数组排序
     * @param $para 排序前的数组
     * return 排序后的数组
     */
    function argSort($para) {
        ksort($para);
        reset($para);
        return $para;
    }
}